package com.example.wxapi.config;

import org.assertj.core.util.Lists;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 任俊杰
 * Date: 2018-05-10
 * Time: 8:44
 */
@Configuration
public class CorsConfig {

    @Bean
    public CorsFilter corsFilter() {

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        String path = "/**";
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowCredentials(true);
        configuration.setAllowedHeaders(Lists.newArrayList("*"));
        configuration.setAllowedMethods(Lists.newArrayList("*"));
        configuration.setAllowedOrigins(Lists.newArrayList("*"));
        configuration.setMaxAge(300L);
        source.registerCorsConfiguration(path, configuration);
        return new OrderedCorsFilter(source);
    }

    static class OrderedCorsFilter extends CorsFilter implements Ordered {

        public OrderedCorsFilter(CorsConfigurationSource configSource) {
            super(configSource);
        }

        @Override
        public int getOrder() {
            return Ordered.HIGHEST_PRECEDENCE + 1;
        }
    }

}
